import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/index';
import { ApiService } from '@core/services/http/api.service';
import { getO, missing, exists, dateFormat, deepClone } from '../../../utils/utils';
import { DialogInputService } from '@core/services/dialog-input.service';
import { differenceInDays } from 'date-fns';
import { SearchService } from '@core/services/search.service';

@Injectable()
export class UtilsService {

  /**条件字段列表**/
  conditionFields: any;

  constructor(protected apiService: ApiService, protected  dialog: DialogInputService, protected searchService: SearchService) {
    // apiService.post('tech.conditionField.findAllByNoPage', {}).subscribe(body => {
    //   if (body) {
    //     this.conditionFields = body;
    //   }
    // });
  }

  /**
   * 功能：ESB服务调用
   * @param {string} method esbId
   * @param body
   * @returns {Observable<any>}
   */
  post(method: string, body: any): Observable<any> {
    return this.apiService.post(method, body);
  }

  exists(param) {
    return exists(param);
  }

  deepClone(param) {
    return deepClone(param);
  }

  /*弹框*/
  openDialog(formId: string, callback: any, dialog: any = null, option: any = null) {
    return this.dialog.openDialog(formId, callback, dialog, option);
  }

  searchData(formId: string, callback: any, option: any) {
    return this.searchService.openDialog(formId, option, callback);
  }

  openContextLink(resultData: any, api: string, config: any) {
    return this.searchService.openContextLink(resultData, api, config);
  }

  /*详情页*/


  /***
   * 功能：判断是否为空
   */
  isEmpty(value) {
    return value === null || value === undefined;
  }

  /**
   * 功能：四舍五入
   * @param {number} x
   * @param {number} scale 小数位数
   * @returns {number}
   */
  round(x: number, scale: number): number {
    return Math.round(x * Math.pow(10, scale)) / Math.pow(10, scale);
  }

  /**
   * 定价执行
   * @returns {Observable<any>}
   */
  pricing(pricingProcedureId: string, ...models: any[]): Observable<any> {
    const m = { 'pricingProcedureId': pricingProcedureId };
    this.conditionFields.forEach(field => {
      const id = field['id'];
      const to = field['to'] || id;
      models.forEach(model => {
        if (model.hasOwnProperty(id)) {
          m[to] = model[id];
        }
      });
    });
    return this.post('tech.pricingProcedure.process', m);
  }

  dateFormat(fmt: string, date: Date) {
    return dateFormat(fmt, date);
  }

  /*date-fns*/
  differenceInDays(dateLeft, dateRight) {
    return differenceInDays(dateLeft, dateRight);
  }

}
